import useMessage from "@/hooks/useMessage";
import { Form, Button, FormInstance, Select } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { addNoticeApi, getMessageListApi, getNoticeDetailApi, updateNoticeApi } from "@/api/modules/system";
import { Notice } from "@/api/interface/system";
import { getUserList } from "@/api/modules/user";
import { debounce } from "lodash-es";

interface PropsType {
	type?: string;
	noticeId?: number;
	onComfirm?: () => void;
}

const NoticeAdd: React.FC<PropsType> = props => {
	const { type, onComfirm, noticeId } = props;
	const { contextHolder, success, error } = useMessage();

	const [noticeDetail, setNoticeDetail] = useState<any>({});

	const getNoticeDetail = async () => {
		const res = await getNoticeDetailApi(noticeId!);
		if (res.code === 200) {
			setNoticeDetail({
				userId: res.data?.user?.id,
				messageId: res.data?.message?.id
			});
			setUserOptions([
				{
					label: res.data?.user.name,
					value: res.data?.user?.id
				}
			]);
		}
	};

	const formRef = useRef<FormInstance | null>(null);

	const onFinish = async (notice: Notice) => {
		try {
			if (type && noticeId) {
				await updateNoticeApi({ ...notice, id: noticeId });
			} else {
				await addNoticeApi(notice);
			}
			onComfirm && onComfirm();
			formRef.current?.setFieldsValue({
				userId: "",
				messageId: ""
			});
			success("发布成功");
		} catch (err) {
			error("发布失败");
		}
	};

	useEffect(() => {
		if (type) {
			getNoticeDetail();
		}
	}, [noticeId]);

	useEffect(() => {
		formRef.current?.resetFields();
		return () => {
			formRef.current?.setFieldsValue({
				content: ""
			});
		};
	}, [noticeDetail]);

	const [messageOptions, setMessageOptions] = useState<{ value: number; label: string }[]>([]);
	const [userOptions, setUserOptions] = useState<{ value: number; label: string }[]>([]);

	const getPreData = async () => {
		try {
			const res = await getMessageListApi(1, 999);
			const messageOptions = res.data.rows.map(item => {
				return {
					value: item.id,
					label: item.content
				};
			});
			setMessageOptions(messageOptions);
		} catch (err) {
			error("获取前置数据失败");
		}
	};

	useEffect(() => {
		getPreData();
	}, []);

	const fetchUserList = async (value: string) => {
		const res = await getUserList(1, 999, { name: value });
		const userOptions = res.data.rows.map(item => {
			return {
				value: item.id,
				label: item.name
			};
		});
		setUserOptions(userOptions);
	};

	const handleSearch = debounce(fetchUserList, 500);

	return (
		<div>
			{contextHolder}
			<Form
				ref={formRef}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 16 }}
				layout="horizontal"
				onFinish={onFinish}
				initialValues={noticeDetail}
			>
				<Form.Item label="消息" rules={[{ required: true }]} name="messageId">
					<Select options={messageOptions} placeholder="选择消息" />
				</Form.Item>
				<Form.Item label="通知人" name="userId">
					<Select
						showSearch
						placeholder="输入通知人关键字"
						defaultActiveFirstOption={false}
						showArrow={false}
						filterOption={false}
						onSearch={handleSearch}
						options={userOptions}
					/>
				</Form.Item>
				<Form.Item wrapperCol={{ offset: 4 }}>
					<Button htmlType="submit" type="primary">
						提交
					</Button>
				</Form.Item>
			</Form>
		</div>
	);
};

export default NoticeAdd;
